<script lang="ts" setup>
import type { AuthenticationInformationProps } from '@croco/framework/libraries';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { AuthenticationLogin } from '@croco/framework/libraries';
import { $t } from '@croco/framework/locales';
import { preferences } from '@croco/framework/preferences';
import { useUserStore } from '@croco/framework/stores';

import { ElNotification } from 'element-plus';

import { getUserDetails, getUserPermissions } from '#/api';
import { service } from '#/api/request';
import VLoginForm from '#/bean/login-form.vue';

defineOptions({ name: 'Login' });

const userStore = useUserStore();

const router = useRouter();

const loading = ref(false);
const loginFormRef = ref();
const captchaImage = ref();
const form = ref<AuthenticationInformationProps>({
    uuid: undefined,
    username: '',
    password: '1234qwer',
    code: undefined,
    remember: false,
    grantType: 'password',
});
const rules = ref({
    username: [{ required: true, message: $t('authentication.usernameTip'), trigger: 'blur' }],
    password: [{ required: true, message: $t('authentication.passwordTip'), trigger: 'blur' }],
    code: [{ required: true, message: $t('authentication.codeTip'), trigger: 'blur' }],
});

const handleCaptcha = () => {
    form.value.uuid = `v${Math.random()}`;
    service
        .get(`/captcha?uuid=${form.value.uuid}`)
        .then((rs) => {
            captchaImage.value = rs ? `data:image/gif;base64,${rs}` : '';
        })
        .catch(() => {});
};

const handleSubmit = (remember: (username: string) => void) => {
    loginFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            loading.value = true;
            service
                .post('/auth/login', { username: 'croco', password: '123456' })
                .then(async (user) => {
                    // 如果成功获取到 accessToken
                    if (user.accessToken) {
                        remember(form.value.username);
                        // 将 accessToken 存储到 accessStore 中
                        userStore.setLoginUser({ username: user.username, token: user.accessToken });

                        // 获取用户信息并存储到 accessStore 中
                        const [fetchUserInfoResult, accessCodes] = await Promise.all([getUserDetails(), getUserPermissions()]);

                        userStore.setUserInfo(fetchUserInfoResult);
                        userStore.setAccessPerms(accessCodes);

                        if (userStore.loginExpired) {
                            userStore.setLoginExpired(false);
                        } else {
                            await router.push(fetchUserInfoResult.homePath || preferences.app.defaultHomePath);
                        }

                        if (fetchUserInfoResult?.realName) {
                            ElNotification({
                                message: `${$t('authentication.loginSuccessDesc')}:${fetchUserInfoResult?.realName}`,
                                title: $t('authentication.loginSuccess'),
                                type: 'success',
                            });
                        }
                    }
                })
                // .then(async ({ loginUser, lastLoginTime }) => {
                //     if (loginUser.token) {
                //         remember();
                //         userStore.setLoginUser(loginUser);
                //
                //         const [details, permissions] = await Promise.all([getUserDetails(), getUserPermissions()]);
                //         userStore.setUserInfo(details);
                //         userStore.setAccessPerms(permissions);
                //
                //         if (userStore.loginExpired) {
                //             userStore.setLoginExpired(false);
                //         } else {
                //             await router.push(details.homePath || preferences.app.defaultHomePath);
                //         }
                //         ElNotification({
                //             message: `${$t('authentication.loginSuccessDesc', [details.nickname, lastLoginTime])}`,
                //             title: $t('authentication.loginSuccess'),
                //             type: 'success',
                //             position: 'bottom-right',
                //         });
                //     }
                // })
                .catch(() => {
                    handleCaptcha();
                })
                .finally(() => {
                    loading.value = false;
                });
        }
    });
};

// onMounted(() => handleCaptcha());
</script>

<template>
    <AuthenticationLogin :loading="loading" :submit="handleSubmit">
        <VLoginForm ref="loginFormRef" v-model="form" :rules="rules" :captcha-image="captchaImage" @captcha="handleCaptcha" />
    </AuthenticationLogin>
</template>
